package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.squareup.okhttp.Request;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.InjectView;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.IntegralModel;
import project.dade.cn.bst.model.MyaddressDate;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;

/**
 * Created by vain zhou on 2016/3/29.
 */
public class WashSubmitActivity extends ZJPBaseBarActivity implements View.OnClickListener {
    @InjectView(R.id.universal_toolBarRTitle)
    TextView tv_tool;
    @InjectView(R.id.tv_address_name)
    TextView name;
    @InjectView(R.id.tv_address_phone)
    TextView phone;
    @InjectView(R.id.tv_address_detail)
    TextView address;
    @InjectView(R.id.layout_unmber)
    RelativeLayout unmber;
    @InjectView(R.id.delivery)
    TextView number;
    @InjectView(R.id.tv_total_money)
    TextView tv_money;
    String money;
    private String id;
    @InjectView(R.id.tv_submit_order)
    TextView sumbit;
    @InjectView(R.id.message)
    EditText message;
    @InjectView(R.id.layout_address)
    RelativeLayout layout_address;
    @InjectView(R.id.ddGoldContentEt)
    EditText clearEditText;
    @InjectView(R.id.txt_jifen_detail)
    TextView  tv_jifen;
    private String getDay="";
    private String getType="";
    private String getMoney="";
    private String getNumber="";
    private int num;
    private KProgressHUD hud;
    private int point;
    private double priced;
    private double integration;
    private String price;
    private  float total_money;
    public static int REQUEST_CODE = 1200;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_washsumbit);
        unmber.setOnClickListener(this);
        sumbit.setOnClickListener(this);
        getDay=getIntent().getStringExtra("time");
        getType=getIntent().getStringExtra("type");
        getMoney=getIntent().getStringExtra("money");
        tv_money.setText(getMoney);
        getNumber=getIntent().getStringExtra("unmber");
        tv_tool.setText("预约洗衣");
        clearEditText.addTextChangedListener(textWatcher);
        layout_address.setOnClickListener(this);
        requestGetAddress();
    }
    public void onResume() {
        super.onResume();
        initRequest();
    }
    private void initRequest() {
        if (AppUtil.isNetworkAvailable(this)) {
            requestGetintegral();
        } else {
            ToastUtil.showShort(WashSubmitActivity.this, R.string.tips_network_error);
        }
    }

    private void requestGetintegral() {
        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在加载")
                .setCancellable(true);
        hud.show();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("mobilephone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Integration).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        hud.dismiss();
                        ToastUtil.showShort(WashSubmitActivity.this, "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        hud.dismiss();
                        LogUtil.i(TAG, "获取个人积分：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取个人积分"))) {
                            IntegralModel model = JSON.parseObject(response, IntegralModel.class);
                            //获取请求成功
                            if (model.getResult() == 0) {
                                //可用积分；
                                integration=model.getData().getPoints();
                                tv_jifen.setText(model.getData().getMoneyToPoint()+""+"积分可抵用1元"+"(可用积分为"+model.getData().getPoints()+")");
                                point=model.getData().getMoneyToPoint();

                            }
                        } else {
                            hud.dismiss();
                            ToastUtil.showShort(WashSubmitActivity.this, NetRequestUtil.requestsError(response, "获取个人积分"));
                            integration=0;

                        }
                    }

                });
    }

    //获取收获地址
    private void requestGetAddress() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Ress).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ToastUtil.showShort(WashSubmitActivity.this, "网络相应失败请稍后再试");
                    }
                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "提交收获地址：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取收货地址"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "提交收获地址：" + model.getData());

                            if (model != null && model.getResult() == 0) {
                                //获取请求成功
                                List<MyaddressDate> myaddressDates = new ArrayList<>();
                                myaddressDates = JSON.parseArray(model.getData(), MyaddressDate.class);
                                if (myaddressDates.size() == 0) {
                                    new MaterialDialog.Builder(WashSubmitActivity.this)
                                            .title(R.string.tips_title)
                                            .titleColor(getResources().getColor(R.color.background_material_dark))
                                            .theme(Theme.LIGHT)
                                            .content("您还未添加过收货地址，是否添加?")
                                            .positiveText(R.string.ok)
                                            .negativeText(R.string.cancel)
                                            .callback(new MaterialDialog.ButtonCallback() {
                                                public void onPositive(MaterialDialog dialog) {
                                                    //确定
                                                    Intent intent = new Intent(WashSubmitActivity.this, MyaddressActivity.class);
                                                    intent.putExtra("mark", "2");
                                                    startActivityForResult(intent, MyaddressActivity.REQUEST_CODE);
                                                }

                                                public void onNegative(MaterialDialog dialog) {

                                                }

                                            }).show();
                                } else {
                                    int position = -1;
                                    for (int i = 0; i < myaddressDates.size(); i++) {
                                        if (myaddressDates.get(i).getStat().equals("1")) {
                                            position = i;
                                        }
                                    }
                                    if (position != -1) {
                                        MyaddressDate test = myaddressDates.get(position);
                                        myaddressDates.remove(position);
                                        myaddressDates.add(0, test);
                                        name.setText("收货人：" + myaddressDates.get(0).getUsername());
                                        phone.setText(myaddressDates.get(0).getPhone());
                                        address.setText(myaddressDates.get(0).getAddress());
                                        id = myaddressDates.get(0).getId();

                                    } else {
                                        name.setText("收货人：" + myaddressDates.get(0).getUsername());
                                        phone.setText(myaddressDates.get(0).getPhone());
                                        address.setText(myaddressDates.get(0).getAddress());
                                        id = myaddressDates.get(0).getId();
                                    }

                                }

                                LogUtil.i(TAG, "获取的地址：" + myaddressDates);
                            }

                        } else {
                            ToastUtil.showShort(WashSubmitActivity.this, NetRequestUtil.requestsError(response, "获取收获地址"));

                        }
                    }

                });
    }
    //动态判断输入框驶入的值
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            if (!TextUtils.isEmpty(clearEditText.getText().toString())) {
                if(Double.valueOf(clearEditText.getText().toString())>integration){
                    ToastUtil.showShort(WashSubmitActivity.this, "积分不足");
                    sumbit.setBackgroundResource(R.drawable.bar_gary);
                    sumbit.setClickable(false);
                }else {
                    sumbit.setClickable(true);
                    if (total_money >=Double.valueOf(clearEditText.getText().toString()) /point) {
                        sumbit.setBackgroundResource(R.drawable.bar_blue);
                        priced = total_money - Double.valueOf(clearEditText.getText().toString()) / point;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        tv_money.setText("¥" + df.format(priced));
                        price=df.format(priced);
                    }else {
                        ToastUtil.showShort(WashSubmitActivity.this, "积分抵扣金额不可大于商品价格");
                        sumbit.setBackgroundResource(R.drawable.bar_gary);
                        sumbit.setClickable(false);
                    }
                }

            }else{
                price=20*num+"";
                tv_money.setText(price);
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_unmber:
                     new MaterialDialog.Builder(this)
                             .title("选择规格")
                             .titleColor(getResources().getColor(R.color.background_material_dark))
                             .theme(Theme.LIGHT)
                             .items(R.array.states)
                             .itemsCallback(new MaterialDialog.ListCallback() {
                                 @Override
                                 public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                     number.setText(text);
                                     num= which+1;
                                     money=20*num+"";
                                     price=money;
                                     total_money=Float.valueOf(money);
                                     tv_money.setText(money);
                                 }
                             })
                             .positiveText(android.R.string.cancel)
                             .show();
                break;
            case R.id.layout_address:
                Intent intent= new Intent(WashSubmitActivity.this, MyaddressActivity.class);
                intent.putExtra("mark","2");
                startActivityForResult(intent, MyaddressActivity.REQUEST_CODE);

                break;

            case R.id.tv_submit_order:
                    //数据验证
                    if (isCheckInput()) {
                        if (AppUtil.isNetworkAvailable(WashSubmitActivity.this)) {
                            requestgoshop();

                        } else {
                            ToastUtil.showShort(WashSubmitActivity.this, R.string.tips_network_error);

                        }
                    }
                break;
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode ==MyaddressActivity.REQUEST_CODE
                && resultCode == MyaddressActivity.REQUEST_CODE) {
            Bundle mBundle = data.getBundleExtra("tempAddress");
            String tv_addres=mBundle.getString("address");
            String tv_name=mBundle.getString("name");
            String tv_phone=mBundle.getString("phone");
            id=mBundle.getString("id");
            LogUtil.i(TAG, "收获：" + id);
            name.setText("收货人：" + tv_name);
            phone.setText(tv_phone);
            address.setText(tv_addres);

        }

    }
    private boolean isCheckInput() {
        //地址不能为空
        if (id==null||id.equals("")) {
            new MaterialDialog.Builder(WashSubmitActivity.this)
                    .title(R.string.tips_title)
                    .titleColor(getResources().getColor(R.color.background_material_dark))
                    .theme(Theme.LIGHT)
                    .content("选择服务地址")
                    .positiveText(R.string.ok)
                    .callback(new MaterialDialog.ButtonCallback() {
                    }).show();

            return false;
        }
        if (TextUtils.isEmpty(number.getText().toString().trim())) {
            new MaterialDialog.Builder(WashSubmitActivity.this)
                    .title(R.string.tips_title)
                    .titleColor(getResources().getColor(R.color.background_material_dark))
                    .theme(Theme.LIGHT)
                    .content("选择规格")
                    .positiveText(R.string.ok)
                    .callback(new MaterialDialog.ButtonCallback() {
                    }).show();

            return false;
        }
        return true;
    }

    private void requestgoshop() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("ProId",AppApplication.getInstance().getSpUtil().getID_Cloth());
        params.put("Quantity",num+"");
        params.put("RecAddress",id);
        params.put("BusinessType",1+"");
        params.put("Remark",message.getText().toString().trim());
        params.put("Integral",clearEditText.getText().toString().trim());
        params.put("Sign", FormatRequest.main(params));

        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.ToBuy).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(WashSubmitActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "提交订单"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "提交订单：" + model.getData());

                            if (model != null && model.getResult() == 0) {
                                if(price.equals("0.0")){
                                    Intent mIntentRegInfo = new Intent(WashSubmitActivity.this,MyorderActivity.class);
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }else {
                                    Intent mIntentRegInfo = new Intent(WashSubmitActivity.this,OrderSucessActivity.class);
                                    mIntentRegInfo.putExtra("number", model.getData());
                                    mIntentRegInfo.putExtra("price", total_money*100);
                                    mIntentRegInfo.putExtra("money",price);
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }
                            }

                        } else {
                            ToastUtil.showShort(WashSubmitActivity.this, NetRequestUtil.requestsError(response, "提交订单失败"));

                        }
                    }

                });
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}
